package org.example.lib.aop;

import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class AopHandler implements InvocationHandler {

    private static final Logger log = LoggerFactory.getLogger(AopHandler.class);
    private final IAspect aspect;
    private final Object target;

    public AopHandler(Object target, IAspect aspect) {
        this.target = target;
        this.aspect = aspect;
    }

    @SneakyThrows
    @Override
    public Object invoke(Object proxy, Method method, Object[] args){
        return aspect.handle(new Handler((arga) -> {
            try {
                return method.invoke(target, arga);
            } catch (IllegalAccessException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        }, args));
    }
}
